<template>
  <up-datetime-picker
    v-model="currentValue"
    :show="internalVisible"
    :mode="mode"
    :min-date="minDate"
    @confirm="onConfirm"
    @cancel="onCancel"
    :title="title"
    :formatter="formatter"
  />
</template>

<script setup>
import { ref, watch, defineProps, defineEmits } from "vue";
import { formatter } from "@/utils";

const props = defineProps({
  pickerVisible: Boolean,
  mode: {
    type: String,
    default: 'datetime'
  }
});

const emit = defineEmits([
  "update:pickerVisible",
  "update:start",
  "update:end",
]);

const internalVisible = ref(false);
const pickingStart = ref(true);

const start = ref(null);
const end = ref(null);
const currentValue = ref(Date.now());
const minDate = ref(0);

const title = ref("开始时间");

watch(
  () => props.pickerVisible,
  (val) => {
    if (val) {
      pickingStart.value = true;
      start.value = null;
      end.value = null;
      currentValue.value = Date.now();
      minDate.value = 0;
      title.value = '开始时间'
    }
    internalVisible.value = val;
  }
);

function onConfirm(e) {
  const selected = e.value ?? Date.now();

  if (pickingStart.value) {
    start.value = selected;
    pickingStart.value = false;
    // minDate.value = selected; // 限制结束时间必须 >= 开始时间
    // currentValue.value = selected;
    uni.showToast({ title: "请继续选择结束时间", icon: "none" });
    title.value = "结束时间";
  } else {
    if (selected < start.value) {
      uni.showToast({ title: "结束时间不能早于开始时间", icon: "none" });
      return;
    }
    end.value = selected;

    emit("update:start", start.value);
    emit("update:end", end.value);
    emit("update:pickerVisible", false);
  }
}

function onCancel() {
  emit("update:pickerVisible", false);
}
</script>
